package cn.touna.jss.modules.custom.adress;

import cn.touna.risk.api.contraints.facet.First;
import cn.touna.risk.api.enums.IntfTypeEnum;
import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.jss.common.cache.HbaseComponent;
import cn.touna.jss.common.entity.CreditQueryRequest;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.util.CollectionUtil;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.credit.service.CreditQueryService;
import cn.touna.jss.modules.custom.adress.entity.ContactList;
import cn.touna.jss.modules.custom.adress.enums.AddressEnum;
import cn.touna.jss.modules.third.jxl.JuXinLiService;
import cn.touna.jss.modules.third.jxl.entity.JuXinLiRequestEntity;
import cn.touna.risk.api.domain.Response;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PropertyFilter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 聚信立通讯录
 * Created by wuwc
 */
@Service
public class JxlAdressListService {
    private static final Logger logger = LogManager.getLogger(JxlAdressListService.class);

    @Autowired
    private JuXinLiService juXinLiService;

    @Autowired
    private HbaseComponent hbaseComponent;

    @Autowired
    CreditQueryService creditQueryService;


    /**
     * 聚信立通讯录
     *
     * @param requestEntity
     * @return
     */
    @ApiMapping(value = "JuXinLi.jxlAddressList", desc = "聚信立.手机通讯录")
    public Response jxlAddressList(JuXinLiRequestEntity requestEntity) {
        try {
            Response validResponse = ValidUtil.valid(requestEntity, First.class);
            if (validResponse != null)
                return validResponse;
            CreditQueryRequest request = new CreditQueryRequest();
            request.setMethod(IntfTypeEnum.JXL_REPORT_DATA.getCode());
            request.setParams((JSONObject) JSONObject.toJSON(requestEntity));
            request.setCacheStrategy("Default");
            request.setMobile(requestEntity.getMobile());
            request.setIdCard(requestEntity.getIdCard());
            String hbaseJxlReport = hbaseComponent.queryCacheData(request);
            String hbaseTianchuangReport = null;
            logger.info("PRO 调用【聚信立通讯录-jxlAddressList-聚信立数据】,查询hbase数据hbaseJxlReport:{}", hbaseJxlReport);
            Map<String, Object> contactMap = new HashMap<>();
            if (!StringUtils.isEmpty(hbaseJxlReport)) {
                JSONObject jsonObject = JSONObject.parseObject(hbaseJxlReport);
                JSONObject reportData = new JSONObject();
                if (jsonObject.get("data") != null) {
                    JSONObject data = JSONObject.parseObject((String) jsonObject.get("data"));
                    reportData = (JSONObject) data.get("report_data");
                } else {
                    reportData = (JSONObject) jsonObject.get("report_data");
                }
                contactMap.put("contact_list", JSON.toJSONString(reportData.get("contact_list")));
            } else {
                request.setMethod("tcredit.getDhbReport");
                request.setIdCard(null);
                hbaseTianchuangReport = hbaseComponent.queryCacheData(request);
//                hbaseTianchuangReport = FileUtils.readFileToString(new File("E:\\jxl_tianchuang.txt"),"UTF-8");
                logger.info("PRO 调用【聚信立通讯录-jxlAddressList-天创数据】,查询hbase数据hbaseJxlReport:{}", hbaseTianchuangReport);
                if (!StringUtils.isEmpty(hbaseTianchuangReport)) {
                    JSONObject jsonObject = JSONObject.parseObject(hbaseTianchuangReport);
                    JSONObject reportData = new JSONObject();
                    if (jsonObject.get("data") != null) {
                        reportData = JSONObject.parseObject(jsonObject.getString("data")).getJSONObject("data");
//                        reportData = (JSONObject) data.get("report_data");
                    } else {
                        reportData = (JSONObject) jsonObject.get("report_data");
                    }
                    contactMap.put("contact_list", JSON.toJSONString(reportData.get("contact_list")));
                }
            }

            if (StringUtils.isEmpty(hbaseJxlReport) && StringUtils.isEmpty(hbaseTianchuangReport)) {
                Response reportResp = juXinLiService.getAccessReportData_v2(requestEntity);
                if (reportResp.getCode().equals("200")) {
                    JSONObject jsonObject = JSONObject.parseObject(reportResp.getData().toString());
                    JSONObject reportData = (JSONObject) jsonObject.get("report_data");
                    contactMap.put("contact_list", JSON.toJSONString(reportData.get("contact_list")));
                }
            }
            //logger.info("PRO 调用【聚信立通讯录-jxlAddressList】,报告显示:{}", txResp);
//            if (org.springframework.util.CollectionUtils.isEmpty(contactMap)) {
//                return new Response().success(AddressEnum.ADDRESS_REPORT_NOTDATA);
//            }
            String addressResult = assembleAddressListData(contactMap, requestEntity);
            return new Response().success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, addressResult);
        } catch (Exception e) {
            e.getStackTrace();
            logger.error("PRO 调用【聚信立通讯录-jxlAddressList】异常,params:{}，msg:{}", requestEntity, e.getMessage());
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_SYSTEM_ERROR, e.getMessage());
        }
    }

    /**
     * 生成通讯录数据
     *
     * @param contactMap
     */
    private String assembleAddressListData(Map<String, Object> contactMap, JuXinLiRequestEntity requestEntity) throws IOException {

        //聚信立通话记录
        String contacts = (String) contactMap.get("contact_list");
        List<ContactList> allContact = (ArrayList) JSONArray.parseArray(contacts, ContactList.class);
        if (allContact == null) {
            allContact = new ArrayList<>();
        }
        logger.info("PRO 调用【聚信立通讯录-jxlAddressList_jxlcontact】,contacts:{}", contacts);
        List<ContactList> jxlCallRecord = new ArrayList();
        Map<String, Integer> phoneMap = new HashMap<>();
        for (ContactList contact : allContact) {
            String name = contact.getNeeds_type();
            if (!StringUtils.isEmpty(name) && ("未知".equals(name) || "有姓名".equals(name))) {
                contact.setName(name);
                jxlCallRecord.add(contact);
                phoneMap.put(contact.getPhone_num(), jxlCallRecord.size() - 1);
            }
        }
        logger.info("PRO 调用【聚信立通讯录-jxlAddressList】,过滤后数据条数:{}", allContact.size());
        //通讯录
        List<ContactList> contactList = new ArrayList<>();
        String hbaseResult = hbaseComponent.queryHbaseContactResult(requestEntity.getMobile());
        logger.info("PRO 调用【聚信立通讯录-jxlAddressList_contacts_list】,params:{} hbaseResult:{}", requestEntity, hbaseResult);
        if (StringUtils.isNotBlank(hbaseResult)) {
            JSONObject jsonHbase = JSONObject.parseObject(hbaseResult);
            JSONArray jsonArray = jsonHbase.getJSONArray("contacts");
            if (jsonArray != null && jsonArray.size() > 0) {
                JSONObject jsonObject = jsonArray.getJSONObject(jsonArray.size() - 1);
                contactList = JSONArray.parseArray(jsonObject.getJSONArray("contacts_list").toString(), ContactList.class);
            }
            if (CollectionUtils.isEmpty(contactList)) {
                jsonArray = jsonHbase.getJSONArray("contacts_list");
                contactList = JSONArray.parseArray(jsonArray.toString(), ContactList.class);
            }
        }


        //昵称
        List<String> nickList = creditQueryService.selectNiceList("1");
        //关键字
        List<String> wordList = creditQueryService.selectNiceList("2");

        //匹配昵称
        List<ContactList> matchNick = new ArrayList<ContactList>();
        //匹配关键字
        List<ContactList> matchWord = new ArrayList<ContactList>();
        //不匹配昵称和关键字
        List<ContactList> notInclud = new ArrayList<ContactList>();
        List<Integer> recordRemoveIndex = new ArrayList<Integer>();
        long starTime = System.currentTimeMillis();
        for (ContactList contact : contactList) {
            String linkPhone = contact.getLink_phone_no();
            linkPhone = linkPhone.trim().replaceAll(" ", "").replaceAll("-", "");
            if (linkPhone.length() > 11 && linkPhone.contains("+86")) {
                linkPhone = linkPhone.substring(linkPhone.length() - 11, linkPhone.length());
            }
            String linkName = contact.getName();
            Integer index = phoneMap.get(linkPhone);
            contact.setTag(index == null ? "1" : "2");
            contact.setPhone_num(linkPhone);
            if (index != null) {
                recordRemoveIndex.add(index);
                ContactList contactRecord = jxlCallRecord.get(index);
                contact.setCall_cnt(contactRecord.getCall_cnt());
                //昵称匹配
                if (nickList.contains(linkName)) {
                    matchNick.add(contact);
                    continue;
                }

                //关键字匹配
                if (wordList.contains(linkName)) {
                    matchWord.add(contact);
                    continue;
                }
                notInclud.add(contact);
            }
        }
        logger.info("PRO 调用【聚信立通讯录-jxlAddressList】,昵称匹配使用时间:{}", System.currentTimeMillis() - starTime);

        //删除所有匹配上的
        removeContactIndex(jxlCallRecord, recordRemoveIndex);
        //批量插入到最后没匹配昵称和关键字的list
        jxlCallRecord.addAll(0, notInclud);
        //批量插入匹配关键字的集合到最前面
        jxlCallRecord.addAll(0, matchWord);
        //批量插入匹配昵称的集合到最前面
        jxlCallRecord.addAll(0, matchNick);
        CollectionUtil.sortListOrderDesc(jxlCallRecord, "call_cnt");
        String contactListStr = JSONArray.toJSONString(jxlCallRecord, new PropertyFilter() {
            @Override
            public boolean apply(Object o, String s, Object o1) {
                if (s.equals("phone_num") || s.equals("name") || s.equals("tag")) {
                    return true;
                }
                return false;
            }
        });
        logger.info("PRO 调用【聚信立通讯录-jxlAddressList】,次数排序后 cloneJxlCallRecord():{}", contactListStr);
        return contactListStr;
    }


    private void removeContactIndex(List<ContactList> jxlCallRecord, List<Integer> recordRemoveIndex) {
        for (Integer index : recordRemoveIndex) {
            jxlCallRecord.remove(index);
        }
    }


}
